const fs   = require("fs")
const path = require("path")
const configPath = "../script/config/"
const config = require(configPath+"action.config")
const dirname = path.join(__dirname,"../script/paint_tool/")
const mapDirs = (dirname)=>{
	console.log(">>"+dirname)
	let fnArr = []
	let fns = fs.readdirSync(dirname);
	fns.forEach(fn=>{
		let nfn = path.join(dirname,fn)
		let stat = fs.statSync(nfn);
		if(stat.isDirectory()){
			mapDirs(nfn,fnArr)
			fnArr.push({
				key:fn.replace(/\w/,(a)=>a.toUpperCase()),
				path:fn,
				dir:true
			})
		}
		else if(stat.isFile()){
			let rfn = filter(fn)
			rfn&&fnArr.push({
				key:rfn,
				path:fn
			})
			// if(rfn)
				// fs.renameSync(nfn,path.join(dirname,rfn+".action.js"))
		}
		createIndexFile(fnArr,dirname)
	})
}
const filter = (fn)=>{
	// path-remove-mng.js
	let reg = /^.*?(?=[\.\-]action\.js)/
	let r = fn.match(reg)
	if(r){
		let rn = r[0].split(/\-/).map(n=>{
			return n.replace(/^[\w]/,(a)=>a.toUpperCase())
		}).join("")
		return rn
	}else
	console.log("***********",fn)
}

const createIndexFile = (fnArr,dirname)=>{
	let dirFnArr = fnArr.filter(fn=>fn.dir).map(d=>d.key).toString()
	let fFnArr = fnArr.filter(fn=>!fn.dir)

	let format = fnArr.map(fn=>{
		let {key,path,dir} = fn
		if(dir)
			return `import * as ${key} from './${path}'`
		path=path.replace(/\.js$/,"")
		return `import ${key} from './${path}'`
	}).join("\n")

	let action = fFnArr.map(fn=>fn.key).join(",\n\t")

	let code = `${format}\nexport {\n\t${action}\n}`
	if(dirFnArr.length>0){
code = 
`${format}\n
let ToolFactory = {\n\t${action}\n}\n
const mergeTools = (dirs)=>{
	dirs.forEach(dir=>{
		for(let k in dir)
			ToolFactory[k] = dir[k]
	})
}
mergeTools([${dirFnArr}])
export default ToolFactory`
	}
	// code = code.replace(/\,/g,",\n\t")
	let indexPath = path.join(dirname,"/index.js")

	if(fs.existsSync(indexPath))
		fs.unlinkSync(indexPath)
	fs.writeFileSync(indexPath,code)
}
// console.log(config)

mapDirs(dirname)



